import Cookie from 'js-cookie';
import clonedeep from 'clonedeep';
import {doCustomTimes, objEqual} from "./tools";
// 与业务结合的工具
export const setTitle = (title) => {
	window.document.title = title || 'admin';
};

export const setToken = (token, tokenName = 'token') => {
	Cookie.set(tokenName, token);
};

export const getToken = (tokenName = 'token') => {
	return Cookie.get(tokenName);
};

/**
 * 把文件放进文件夹
 * @param folderList
 * @param fileList
 */
export const putFileInFolder = (folderList, fileList) => {
	// 深拷贝
	const folderListClone = clonedeep(folderList);
	const fileListClone = clonedeep(fileList);
	return folderListClone.map(folderItem => {
		// 文件夹id
		const folderId = folderItem.id;
		// 文件列表长度作为index
		let index = fileListClone.length;
		while (--index >= 0) {
			// 最后一个文件对象
			const fileItem = fileListClone[index];
			// folderId和文件的folder_id相同的，说明属于文件夹下的文件，添加到文件夹下
			if (fileItem.folder_id === folderId) {
				// 删除元素
				const file = fileListClone.splice(index, 1)[0];
				file.title = file.name;
				// 存到文件夹下
				if (folderItem.children) folderItem.children.push(file);
				else folderItem.children = [file];
			}
		}
		// 文件夹类型
		folderItem.type = 'folder';
		return folderItem;
	})
};

/**
 * 把文件夹转换成树状结构
 * @param folderList
 */
export const transferFolderToTree = folderList => {
	if (!folderList.length) return [];
	const folderListClone = clonedeep(folderList);
	// 当前文件夹id
	const handle = id => {
		const arr = [];
		// 遍历文件夹
		folderListClone.forEach(folder => {
			// 如果 folder.folder_id === id，说明folder属于文件夹为id的子文件夹
			if (folder.folder_id === id) {
				// 递归
				const children = handle(folder.id);
				if (folder.children) folder.children = [].concat(folder.children, children);
				else folder.children = children;
				folder.title = folder.name;
				arr.push(folder);
			}
		});
		return arr;
	};
	return handle(0);
};

/**
 * 判断tree是否展开
 * @param folderTree
 * @param id
 */
export const expandSpecifiedFolder = (folderTree, id) => {
	return folderTree.map(item => {
		if (item.type === 'folder') {
			if (item.id === id) {
				item.expand = true;
			} else {
				if (item.children && item.children.length) {
					item.children = expandSpecifiedFolder(item.children, id);
					// 如果子节点展开，父级也需要展开
					item.expend = !!item.children.some(child => {
						return child.expend === true;
					});
				}
			}
		}
		return item;
	});
}

export const downloadFile = ({url, params}) => {
	const form = document.createElement('form');
	form.setAttribute('action', url);
	form.setAttribute('method', 'post');
	for (const key in params) {
		if (params.hasOwnProperty(key)) {
			const input = document.createElement('input');
			input.setAttribute('type', 'hidden');
			input.setAttribute('name', key);
			input.setAttribute('value', params[key]);
			form.appendChild(input);
		}
	}
	document.body.appendChild(form);
	form.submit();
	form.remove();
}

export const routeEqual = (route1, route2) => {
	const params1 = route1.params || {};
	const params2 = route2.params || {};
	const query1 = route1.query || {};
	const query2 = route2.query || {};
	return route1.name === route2.name && objEqual(params1, params2) && objEqual(query1, query2);
}

/**
 * 判读路由是否存在
 */
export const routeHasExist = (tabList, routeItem) => {
	let len = tabList.length;
	let res = false;
	doCustomTimes(len, index => {
		if (routeEqual(tabList[index], routeItem)) res = true;
	});
	return res;
}

const getKeyValueArr = obj => {
	let arr = [];
	Object.entries(obj).sort((a, b) => {
		return a[0] - b[0];
	}).forEach(([_key, _val]) => arr.push(_key, _val));
	return arr;
};

export const getTabNameByRoute = route => {
	const {name, params, query} = route;
	let res = name;
	if (params && Object.keys(params).length) res += ':' + getKeyValueArr(params).join('_');
	if (query && Object.keys(query).length) res += '&' + getKeyValueArr(query).join('_');
	return res;
}

/**
 * 字符串转对象
 * @param id 字符串
 * @param splitStr 切割规则
 */
const getObjBySplitStr = (id, splitStr) => {
	let splitArray = id.split(splitStr);
	let element = splitArray[splitArray.length - 1];
	let keyValArr = element.split('_'); // &a_111_b_222
	let res = {};
	let i = 0;
	let len = keyValArr.length;
	while (i < len) {
		res[keyValArr[i]] = keyValArr[i + 1]; // [a,111,b,222] => {a:111,b:222}
		i += 2;
	}
	return res;
};

export const getRouteById = id => {
	const res = {};
	if (id.includes('&')) {
		res.query = getObjBySplitStr(id, '&');
		id = id.split('&')[0];
	}
	if (id.includes(':')) {
		res.params = getObjBySplitStr(id, ':');
		id = id.split(':')[0];
	}
	res.name = id;
	return res;
};

export const getOpenArrByName = (name, routerList) => {
	let arr = [];
	routerList.some(item => {
		if (item.name === name) {
			arr.push(item.name);
			return true;
		}
		if (item.children && item.children.length) {
			let childArr = getOpenArrByName(name, item.children);
			if (childArr.length) {
				arr = arr.concat(item.name, childArr);
				return true;
			}
		}
	});
	return arr;
};

/**
 * 本地存储
 * @param name
 * @param value
 */
export const localSave = (name, value) => {
	return localStorage.setItem(name, value);
};

/**
 * 本地读取
 * @param name
 * @returns {string}
 */
export const localRead = name => {
	return localStorage.getItem(name);
};
